package com.mallcai.bigdata.ladon.vo;

import java.util.*;

/**
 * @author feixy
 * @version 1.0
 * @date 2019-07-19 14:57
 */
public class QueryParamCollector {

    private final String sql;
    private List<ParamHolder> list = new LinkedList<>();

    public QueryParamCollector(String sql) {
        this.sql = sql;
    }

    public void add(ParamHolder obj){
        list.add(obj);
    }


    public QueryParam toParam(){
        Map<Integer, Object> params = new LinkedHashMap<>();
        String sql = this.sql;
        int index = 1;
        for (ParamHolder paramHolder : this.list){
            sql = paramHolder.replaceSql(sql);
            if(paramHolder.usePlaceHolder){
                params.put(index++, paramHolder.values);
            }
        }
        QueryParam queryParam = new QueryParam();
        queryParam.setRawSql(sql);
        queryParam.setParams(params);
        return queryParam;
    }

    public static class ParamHolder{

        private String paramName;

        private Object values;

        private boolean usePlaceHolder;


        public ParamHolder(String paramName, Object value) {
            this.paramName = paramName;
            if(value instanceof Collection){
                this.values = ((Collection)value).toArray();
            } else {
                this.values = value;
            }
            this.usePlaceHolder = true;
        }

        public void setUsePlaceHolder(boolean usePlaceHolder) {
            this.usePlaceHolder = usePlaceHolder;
        }

        public String replaceSql(String sql){
            String temp = "?";
            if(!usePlaceHolder){
                temp = String.valueOf(this.values);
            }
            return sql.replaceAll(String.format("#%s#", paramName), temp);
        }
    }
}
